package com.qa.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.qa.pojo.qpy_configinfo;

/***
 * 操作网易云频道
 * 
 * @author Administrator
 * 
 */
public class PostWYY {
	/***
	 * 根据传递的类型，进行直播频道的相关操作
	 * 
	 * @param urlType
	 * @param qpyConfiginfos
	 * @param macInfo
	 * @return
	 */
	public static String postWyy(String urlType, qpy_configinfo qpyConfiginfos,
			String macInfo) {
		String returnString = "";
		DefaultHttpClient httpClient = new DefaultHttpClient();
		String url = "https://vcloud.163.com/app/channel/" + urlType;
		if (urlType.equals("stats")) {
			url = "https://vcloud.163.com/app/channelstats";
		}
		HttpPost httpPost = new HttpPost(url);

		String appKey = qpyConfiginfos.getAppkey();
		String appSecret = qpyConfiginfos.getAppsecret();
		String nonce = "1";
		String curTime = String.valueOf((new Date()).getTime() / 1000L);
		String checkSum = CheckSumBuilder
				.getCheckSum(appSecret, nonce, curTime);// 参考 计算CheckSum的java代码

		// 设置请求的header
		httpPost.addHeader("AppKey", appKey);
		httpPost.addHeader("Nonce", nonce);
		httpPost.addHeader("CurTime", curTime);
		httpPost.addHeader("CheckSum", checkSum);
		httpPost.addHeader("Content-Type", "application/json;charset=utf-8");

		// 设置请求的参数
		StringEntity params = null;
		try {
			if (urlType.equals("create")) {
				params = new StringEntity("{\"name\":\"" + macInfo
						+ "\", \"type\":0}", "utf-8");
			} else if (urlType.equals("delete")) {
				params = new StringEntity("{\"cid\":\"" + macInfo + "\"}",
						"utf-8");
			} else if (urlType.equals("pause")) {
				params = new StringEntity("{\"cid\":\"" + macInfo + "\"}",
						"utf-8");
			} else if (urlType.equals("resume")) {
				params = new StringEntity("{\"cid\":\"" + macInfo + "\"}",
						"utf-8");
			} else if (urlType.equals("stats")) {
				params = new StringEntity("{\"cid\":\"" + macInfo + "\"}",
						"utf-8");
			}
			httpPost.setEntity(params);

			// 执行请求
			HttpResponse response = httpClient.execute(httpPost);

			// 打印执行结果
			returnString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "程序异常";
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "程序异常";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "程序异常";
		}
		return returnString;
	}

}
